# encoding=utf-8
import requests
import datetime
import os
import time
from tomorrow import threads

class Xiaofeixiang(object):
    url = 'http://www.avt7.com/Home/AirportMetarInfo?airport4Code={}'
    base_dir = './'
    headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36',}
    airport_code_file = './spider/avt7/airport_4_code.txt'
    def __init__(self):
        super().__init__()
    
    def get_airport_4_code(self):
        list_code = open(self.airport_code_file).read().split(',')
        return list_code
    
    # 下载所有机场的信息，机场信息最快的3个半小时更新一次，需要每4个小时爬一次
    def request(self):
        list_code = self.get_airport_4_code()
        for code in list_code:
            response = requests.get(self.url.format(code), headers=self.headers)
            response.encoding = 'utf8'
            save_dir = self.get_save_dir()
            save_file = code + '.json'
            save_file_path = os.path.join(save_dir, save_file)
            self.file_write(save_file_path, response.text)

    # 创建json文件夹并返回文件夹目录
    def get_save_dir(self):
        now_date = datetime.datetime.now().strftime('%Y%m%d%H')
        save_dir = os.path.join(self.base_dir, now_date)
        # 如果文件夹不存在则创建
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        return save_dir
    
    # 创建json文件夹并返回文件夹目录
    def file_write(self, file_path, content, mode='a', encoding='utf8'):
        '''
        1. 作用:创建文件并把content的内容写入到文件file_path中
        2. 参数:
            file_path:文件路径
            content:文件写入的内容
            mode:文件读写的模式,默认为'w'
            encoding:文件编码,默认为'utf8'
        3. 返回值:None
        '''
        f = open(file=file_path, mode=mode, encoding=encoding)
        f.write(content)
        f.close()

if __name__ == '__main__':
    xiaofeixiang = Xiaofeixiang()
    xiaofeixiang.request()